<?php
namespace app\chat\controller;
/**
 * 聊天主逻辑
 * 主要是处理 onMessage onClose 
 */
use \GatewayWorker\Lib\Gateway;

class Events
{
	//当客户端连接时触发
	
   public static function onConnect($client_id)
    {
        // 向当前client_id发送数据
        //Gateway::sendToClient($client_id, "Hello $client_id\r\n");
        // 向所有人发送
       // Gateway::sendToAll("$client_id login\r\n");

        Gateway::sendToClient($client_id,json_encode([
           'type'=>'login',
           'client_id'=>$client_id
       ]));

    }
   /**
    * 有消息时
    * @param int $client_id
    * @param mixed $message
    */
   public static function onMessage($client_id, $message)
   {

       $data = json_decode($message,true);
       print_r($data);
       if ($data['type'] == 'reg'){
           Gateway::bindUid($client_id, $data['data']['uid']);
           echo "用户 " . $data['data']['uid'] . "上线\n";
           $return = [
               'type' => 'msg',
               'data' => "用户：".$data['data']['uid']."上线  client_id:$client_id"
           ];
           Gateway::sendToAll(json_encode($return));
       }else if ($data['type'] == 'chatMessage'){
           if ($data['data']['type'] == 'friend'){ // 单聊
               Gateway::sendToUid($data['data']['js_userid'], json_encode($data['data']));
           }
       }else if ($data['type'] == 'ping'){
          echo "ping\n";
          return false;
       }
   }
   
   /**
    * 当客户端断开连接时
    * @param integer $client_id 客户端id
    */
   public static function onClose($client_id)
   {

   }
  
}